package org.ssp.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import org.ssp.pojo.Token;
import org.ssp.service.CoreService;

import net.sf.json.JSONObject;

public class CommonUtil {
	
	public static String TOKEN_URL="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
	

	/**
	 * java发起https请求的接口
	 * @param url 请求的https地址
	 * @param method 请求的方式
	 * @param outStream 请求的参数
	 * @return  返回json结果
	 * @throws Exception 
	 */
	
	public static String httpsRequest(String url1,String method,String outputStr) throws  Exception{
		StringBuffer buffer=null;

		//创建证书
		//创建SSL context
		SSLContext sslContext=SSLContext.getInstance("SSL","SunJSSE");
		TrustManager[] tm={new MyX509TrustMannger()};
		//初始化
		sslContext.init(null, tm,new java.security.SecureRandom());
		//获取sslSocketFactory对象
		SSLSocketFactory ssf=sslContext.getSocketFactory();
		

		URL url=new URL(url1);
		HttpsURLConnection conn=(HttpsURLConnection) url.openConnection();
		conn.setRequestMethod(method);
		//设置当前实例使用的SSLSocketFactory			
		conn.setSSLSocketFactory(ssf);
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.connect();
		
		//io流

		//往服务器内写内容

		if(null!=outputStr){
			System.out.println("enter the writting");
			OutputStream os=conn.getOutputStream();
			os.write(outputStr.getBytes("utf-8"));//如何得到byte数组
			System.out.println("over");
			os.close();
		}

		//读取服务器返回的内容
		InputStream is=conn.getInputStream();
		InputStreamReader isr=new InputStreamReader(is,"utf-8");
		BufferedReader br=new BufferedReader(isr);
		buffer=new StringBuffer();
		String line=null;
		while((line=br.readLine())!=null){
			buffer.append(line);
		}
		
		return buffer.toString();
	}
	
	//根据返回的json字符串解析出access_token参数
	
	public static Token getAccessToken(String appid,String appsecret) throws Exception{
		Token token=null;
		//拼接请求地址
//		String requestUrl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxf34da76143f5050d&secret=7a6df503a9afaa70601d652cfb99b16d";
		String requestUrl=CommonUtil.TOKEN_URL.replace("APPID", CoreService.AppID).replace("APPSECRET",CoreService.AppSecret);
		System.out.println("token:->"+requestUrl);
		//调用接口,发起https请求
		String json=CommonUtil.httpsRequest(requestUrl, "GET", null);
		//通过json-lib的API把json字符串转化成java对象
		JSONObject jsonObject=JSONObject.fromObject(json);
		String access_token=jsonObject.getString("access_token");
		int expires_in=jsonObject.getInt("expires_in");
	
		token=new Token();
		token.setAccessToken(access_token);
		token.setExpiresIn(expires_in);
		
		return token;
	}
	
	/**
	 * java发起http请求
	 * @param picurl
	 * @param method
	 * @param outputStr
	 * @return 返回josn结果
	 * @throws IOException
	 */
	
    public static String httpRequest(String picurl,String method,String outputStr) throws IOException {
    	StringBuffer buffer=null;
		URL url=null;
		try {
			
			url = new URL(picurl);
			HttpURLConnection conn=(HttpURLConnection) url.openConnection();
			conn.setRequestMethod(method);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.connect();
	
			//往服务器写内容
			if(null!=outputStr){
				OutputStream os=conn.getOutputStream();
				os.write(outputStr.getBytes("utf-8"));
				os.close();	
				
			}
						
			//读取服务器返回的内容
			InputStream is=conn.getInputStream();
			InputStreamReader isr=new InputStreamReader(is,"utf-8");
			BufferedReader br=new BufferedReader(isr);
			buffer=new StringBuffer();
			String line=null;
			while((line=br.readLine())!=null){
				buffer.append(line);
			}	
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		return buffer.toString();
		
	}
    /**
     * 对url进行utf-8编码
     * @param url
     * @return
     */
    public static String urlEncodeUTF8(String url){
    	String result=url;
    	try {
			result=java.net.URLEncoder.encode(result,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
    	System.out.println(result);
    	return result;   	
    }
    
    /**
     * 对url进行utf-8解码
     * @param url
     * @return
     */
    public static String urlDecodeUTF8(String url){
    	String result=url;
    	if(null!=result){
    		try {
    			result=java.net.URLDecoder.decode(result,"UTF-8");
    		} catch (UnsupportedEncodingException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		
    	}
    	return result;
    }
	
}
